package com.szs.service.impl;

import com.szs.exception.ClassHasStudentsException;
import com.szs.exception.DeptHasEmpException;
import com.szs.mapper.DeptMapper;
import com.szs.pojo.Dept;
import com.szs.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;
    @Override
    public List<Dept> findAll() {

        return deptMapper.findAll();
    }
    /*
    * 根据id删除部门
    * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(Integer id) {
        Optional<Dept> deptOptional = deptMapper.findById(id);
        if (deptOptional.isEmpty()) {
            throw new IllegalArgumentException("部门未找到");
        }
        Dept dept = deptOptional.get();

        if (dept.getEmpList() != null && !dept.getEmpList().isEmpty()) {
            throw new DeptHasEmpException("对不起, 该部门下有员工, 不能直接删除");
        }
        deptMapper.deleteById(id);
    }

    @Override
    public void add(Dept dept) {
        //补全基础属性，-createTime，updateTime
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());

        //调用Mapper接口方法插入数据
        deptMapper.insert(dept);
    }

    @Override
    public Dept getById(Integer id) {
        return deptMapper.getById(id);
    }

    @Override
    public void update(Dept dept) {
        //1 补全基础属性 updateTime
        dept.setUpdateTime(LocalDateTime.now());

        //2 调用Mapper接口方法更新部门
        deptMapper.update(dept);
    }
}
